package cn.dankal.flyaudio.current.post.detail;

import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.TouchDelegate;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.request.target.BitmapImageViewTarget;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.dankal.basiclib.GlideApp;
import cn.dankal.basiclib.base.recyclerview.BaseRecyclerViewAdapter;
import cn.dankal.basiclib.base.recyclerview.BaseRecyclerViewHolder;
import cn.dankal.basiclib.util.StringUtil;
import cn.dankal.basiclib.util.TimeUtil;
import cn.dankal.basiclib.util.image.PicUtils;
import cn.dankal.basiclib.widget.DkUserImageView;
import cn.dankal.business.pojo.CommentBean;
import cn.dankal.flyaudio.R;

import static cn.dankal.basiclib.util.DisplayHelper.dp2px;

/**
 * 详情页面下的评论适配器
 */
public class CommentAdapter extends BaseRecyclerViewAdapter<CommentBean> {

    private boolean flag;
    private int showSize = 3;

    private ViewClickListen viewClickListen;

    private CommentReplyAdapter.OnChoiceByUserToReplyListener listener;

    public CommentAdapter(boolean flag) {
        this.flag = flag;
    }

    public void setViewClickListen(ViewClickListen viewClickListen) {
        this.viewClickListen = viewClickListen;
    }

    public void setListener(CommentReplyAdapter.OnChoiceByUserToReplyListener listener) {
        this.listener = listener;
    }

    private void blowUpArea(View view) {
        Rect outRect = new Rect();
        int offset = dp2px(context, 30);
        outRect.left -= offset;
        outRect.top -= offset;
        outRect.right += offset;
        outRect.bottom += offset;
        view.getHitRect(outRect);
        TouchDelegate delegate = new TouchDelegate(outRect, view);
        ((View) view.getParent()).setTouchDelegate(delegate);
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    protected int getLayoutResId(int viewType) {
        return R.layout.post_item_rv_comment;
    }

    @Override
    protected BaseRecyclerViewHolder getViewHolder(ViewGroup parent, View rootView, int viewType) {
        return new ViewHolder(rootView);
    }

    @Override
    public void onBindViewHolder(@NonNull BaseRecyclerViewHolder<CommentBean> holder, int position, @NonNull List<Object> payloads) {
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
            return;
        }
        CommentBean commentBean = findData(position);
        TextView mTvGood = holder.findViewById(R.id.tv_good);

        if (commentBean != null) {
            mTvGood.setText(commentBean.likeNumber);
            if (commentBean.isPraise > 0) {
                Drawable drawable = context.getResources().getDrawable(R.mipmap.pic_home_good_2);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//必须设置图片大小，否则不显示
                mTvGood.setCompoundDrawables(drawable, null, null, null);
            } else {
                Drawable drawable = context.getResources().getDrawable(R.mipmap.pic_home_good_2_formal);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//必须设置图片大小，否则不显示
                mTvGood.setCompoundDrawables(drawable, null, null, null);
            }
        }
    }


    public class ViewHolder extends BaseRecyclerViewHolder<CommentBean> {

        // 上次点赞的时间
        private long lastPraiseTime = 0L;
        // 上次点赞的UUID
        private String lastPraiseUUID;
        // 暴力点击的阻隔时间 单位：ms
        private long barrierTime = 1200L;

        private CommentBean commentBean;

        // 头像
        @BindView(R.id.iv_header)
        DkUserImageView mIvHeader;
        // 姓名
        @BindView(R.id.tv_name)
        TextView mTvName;
        // 评论内容
        @BindView(R.id.tv_content)
        TextView mTvContent;
        // 评论时间
        @BindView(R.id.tv_time)
        TextView mTvTime;

        @BindView(R.id.tv_good)
        TextView mTvGood;
        // 回复评论操作
        @BindView(R.id.rv_comement_reply)
        RecyclerView mRvComementReply;
        // 查看更多评论
        // 回复评论
        @BindView(R.id.iv_reply)
        ImageView mIvReply;
        // 二级评论
        @BindView(R.id.ll_second)
        LinearLayout mLLSecond;


        public ViewHolder(View itemView) {
            super(itemView);
        }

        @Override
        public void onBindData(CommentBean data, int position) {
            // 扩大可点击得区域
            blowUpArea(mIvReply);
            bindData(data, position);
        }

        @OnClick({R.id.tv_good})
        public void onRelyClick(View v) {

            // 防止暴力点击 防止相同的位置重复点击
            if (lastPraiseUUID == commentBean.uuid && lastPraiseTime + barrierTime > System.currentTimeMillis()) {
                lastPraiseTime = System.currentTimeMillis();
                return;
            } else {
                lastPraiseTime = System.currentTimeMillis();
                lastPraiseUUID = commentBean.uuid;
            }
            if (listener != null && commentBean != null) {
                //  isPraise 表示已经点赞
                if (commentBean.isPraise > 0) {
                    listener.praiseCancel(commentBean.uuid, String.valueOf(commentBean.type), commentBean.getCommentPosition());
                } else {
                    listener.praise(commentBean.uuid, String.valueOf(commentBean.type), commentBean.getCommentPosition());
                }
            }
        }

        @OnClick({R.id.iv_header, R.id.tv_name, R.id.tv_content, R.id.iv_reply})
        public void onViewClicked(View view) {

            if (listener != null && commentBean != null) {
                listener.innerComment(commentBean.name,
                        String.valueOf(commentBean.uuid),
                        String.valueOf(commentBean.userUuid), commentBean.getCommentPosition());

                if (viewClickListen != null) {
                    int[] decorViewLocationInScreen = new int[2];
                    view.getLocationOnScreen(decorViewLocationInScreen);
                    viewClickListen.viewClick(decorViewLocationInScreen[1]);
                }
            }

        }

        private void bindData(CommentBean bean, int position) {
            if (bean == null) {
                return;
            }
            commentBean = bean;
            commentBean.setCommentPosition(position);

            //PicUtils.loadAvatar(StringUtil.safeString(bean.avatar), mIvHeader);
            GlideApp.with(context).asBitmap().centerCrop().error(R.mipmap.pic_ill_4).load(PicUtils.QINIU_DOMAIN + bean.avatar).into(new BitmapImageViewTarget(mIvHeader) {
                @Override
                protected void setResource(Bitmap resource) {
                    RoundedBitmapDrawable circularBitmapDrawable =
                            RoundedBitmapDrawableFactory.create(context.getResources(), resource);
                    circularBitmapDrawable.setCircular(true);
                    mIvHeader.setImageDrawable(circularBitmapDrawable);
                }
            });

            mTvName.setText(StringUtil.safeString(bean.name));
            mTvContent.setText(StringUtil.safeString(bean.content));
            mTvTime.setText(TimeUtil.getFgtime(bean.createTime));

            mIvReply.setVisibility(flag ? View.VISIBLE : View.GONE);
            mTvGood.setText(bean.likeNumber);
            if (bean.isPraise > 0) {
                Drawable drawable = context.getResources().getDrawable(R.mipmap.pic_home_good_2);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//必须设置图片大小，否则不显示
                mTvGood.setCompoundDrawables(drawable, null, null, null);
            } else {
                Drawable drawable = context.getResources().getDrawable(R.mipmap.pic_home_good_2_formal);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//必须设置图片大小，否则不显示
                mTvGood.setCompoundDrawables(drawable, null, null, null);
            }

            List<CommentBean.SecondCommentsBean> second_comments = bean.list;
            if (second_comments == null || second_comments.size() == 0) {
                mLLSecond.setVisibility(View.GONE);
                return;
            }

            mLLSecond.setVisibility(View.VISIBLE);
            CommentReplyAdapter commentReplyAdapter;
            commentReplyAdapter = new CommentReplyAdapter(bean.uuid);
            if (listener != null) {
                commentReplyAdapter.setListener(listener);
            }
            mRvComementReply.setLayoutManager(new LinearLayoutManager(context));
            mRvComementReply.setAdapter(commentReplyAdapter);

            commentReplyAdapter.updateData(second_comments);
        }

    }

}
